/** 
 * FileName:     Order.java 
 * @Description: TODO(用一句话描述该文件做什么) 
* All rights Reserved, Designed By hnkeystone 
 * Copyright:    Copyright(C) 2010-2011 
 * Company       坚磐科技 
 * @author:    冯辉 
 * @version    V1.0  
 * Createdate:         2017-3-29 下午6:24:26 
 * 
 * Modification  History: 
 * Date         Author        Version        Discription 
 * ----------------------------------------------------------------------------------- 
 * 2017-3-29       hnkeystone.com          1.0             1.0 
 * Why & What is modified: <修改原因描述> 
 */  
package com.fh.controller.order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.fh.controller.base.BaseController;
import com.fh.entity.OrderEntity;
import com.fh.entity.OrderGoodsSpecEntity;
import com.fh.entity.Page;
import com.fh.entity.SupplierEntity;
import com.fh.entity.system.User;
import com.fh.service.order.OrderService;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.JsonResult;
import com.fh.util.PageData;
/** 
 * @ClassName:     Order 
 * @Description:TODO(这里用一句话描述这个类的作用) 
 * @author:    冯辉 
 * @date:        2017-3-29 下午6:24:26 
 *  
 */
@Controller
@RequestMapping(value = "/order")
public class Order extends BaseController {
	@Resource
	private OrderService orderService;
	/**
	 * 订单收款
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/ordercollection")
	public String auditsetting()throws Exception{
		return "order/ordercollection";
	}
	
	/**
	 * 订单确认页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/orderconfirm")
	public String orderconfirm()throws Exception{
		return "order/orderconfirm";
	}
	/**
	 * 订单发货页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/orderdelivery")
	public String orderdelivery()throws Exception{
		return "order/orderdelivery";
	}

	/**
	 * 订单配货页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/orderprepare")
	public String orderprepare()throws Exception{
		return "order/orderprepare";
	}
	
	
	/**
	 * 确认订单列表
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/querySureOrderList")
	@ResponseBody
	public Object querySureOrderList(HttpServletRequest request,int page,int rows) throws Exception{
		String orderNo=request.getParameter("orderNo");//订单编号
		String name=request.getParameter("name");//顾客名字
		String startTime=request.getParameter("startTime");//开始时间
		String endTime=request.getParameter("endTime");//结束时间
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		User user = (User)session.getAttribute(Const.SESSION_USER);
			//分页对象
			Page pd = new Page();
			//设置参数
			PageData pda = new PageData();
			pda.put("orderNo", orderNo);
			pda.put("name", name);
			pda.put("startTime", startTime);
			pda.put("endTime", endTime);
			pda.put("id", user.getSupplierid());
			pd.setPd(pda);
			
			//订单总条数
		    int totalCount=orderService.queryOrderCount(pd);
			pd.setPageParams(totalCount, rows, page);
			//订单列表
			List<OrderEntity> list=orderService.querySureOrderList(pd);
			//把结果集和总条数返回
		    Map<String,Object> map=new HashMap<String,Object>();
		    map.put("total", totalCount);
		    map.put("rows", list);
			return map;
	}

	/**
	 * 确认配货列表
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/queryPreOrderList")
	@ResponseBody
	public Object queryPreOrderList(HttpServletRequest request,int page,int rows) throws Exception{
		String orderNo=request.getParameter("orderNo");//订单编号
		String name=request.getParameter("name");//顾客名字
		String startTime=request.getParameter("startTime");//开始时间
		String endTime=request.getParameter("endTime");//结束时间
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		User user = (User)session.getAttribute(Const.SESSION_USER);
		
			//分页对象
			Page pd = new Page();
			//订单总条数
		    int totalCount=orderService.queryOrderPreCount(pd);
			pd.setPageParams(totalCount, rows, page);
			//设置参数
			PageData pda = new PageData();
			pda.put("orderNo", orderNo);
			pda.put("name", name);
			pda.put("startTime", startTime);
			pda.put("endTime", endTime);
			pda.put("id", user.getSupplierid());
			pd.setPd(pda);
			//订单列表
			List<OrderEntity> list=orderService.queryPreOrderList(pd);
			//把结果集和总条数返回
		    Map<String,Object> map=new HashMap<String,Object>();
		    map.put("total", totalCount);
		    map.put("rows", list);
			return map;
	}
	
	
	/**
	 * 订单发货列表
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/querySendOrderList")
	@ResponseBody
	public Object querySendOrderList(HttpServletRequest request,int page,int rows) throws Exception{
		String orderNo=request.getParameter("orderNo");//订单编号
		String name=request.getParameter("name");//顾客名字
		String startTime=request.getParameter("startTime");//开始时间
		String endTime=request.getParameter("endTime");//结束时间
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		User user = (User)session.getAttribute(Const.SESSION_USER);
		
			//分页对象
			Page pd = new Page();
			//设置参数
			PageData pda = new PageData();
			pda.put("orderNo", orderNo);
			pda.put("name", name);
			pda.put("startTime", startTime);
			pda.put("endTime", endTime);
			pda.put("id", user.getSupplierid());
			pd.setPd(pda);
			
			//订单总条数
		    int totalCount=orderService.querySendOrderCount(pd);
			pd.setPageParams(totalCount, rows, page);
			
			//订单列表
			List<OrderEntity> list=orderService.querySendOrderList(pd);
			//把结果集和总条数返回
		    Map<String,Object> map=new HashMap<String,Object>();
		    map.put("total", totalCount);
		    map.put("rows", list);
			return map;
	}

	/**
	 * 供应商取消订单
	 * @return
	 */
	@RequestMapping(value="/removeorder")
	@ResponseBody
	public JsonResult removeorder(String id){
		JsonResult result=new JsonResult();
		PageData pd = new PageData();
		int status=-2;
		pd.put("id", id);
		pd.put("orderStatus", status);
		try {
			//取消订单--修改状态
			int flag=orderService.updateOrderStatus(pd);
			//查询订单基本信息
			OrderEntity order = orderService.findOneOrder(pd);
			// 添加订单历史表
			pd.put("orderHistoryID", UUID.randomUUID().toString());
			pd.put("orderStatus", status);
			pd.put("createTime", DateUtil.getTime());
			pd.put("createBy", order.getSupplierID());
			orderService.createOrderHistory(pd);
			List<OrderGoodsSpecEntity> orderDetailList = orderService
					.OrderGoodsSpecEntity(pd);
			for (int i = 0; i < orderDetailList.size(); i++) {
				OrderGoodsSpecEntity ode = orderDetailList.get(i);
				// 将该订单商品预约库存量增加到库存量
				pd.put("inventory", ode.getInventory() + ode.getNumber());
				// 去除已取消的预约库存量
				pd.put("reserveCount", ode.getReserveCount() - ode.getNumber());
				pd.put("goodsSpecId", ode.getGoodsSpecId());
				orderService.updateGoodsSpecInventory(pd);
			}
			if(flag==1){
				result=JsonResult.success("200", "取消成功");
			}else{
				result=JsonResult.error("300", "取消失败");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return result;
	}
	
	/**
	 * 订单配货的处理
	 * @return
	 */
	@RequestMapping(value="/orderPre")
	@ResponseBody
	public JsonResult orderPre(String id){
		JsonResult result=new JsonResult();
		PageData pd = new PageData();
		int status = 3;
		pd.put("id", id);
		pd.put("orderStatus", status);//订单发货
		try {
			int times = orderService.updateOrderStatus(pd);
			//查询订单基本信息
			OrderEntity order = orderService.findOneOrder(pd);
			// 添加订单历史表
			pd.put("orderHistoryID", UUID.randomUUID().toString());
			pd.put("orderStatus", status);
			pd.put("createTime", DateUtil.getTime());
			pd.put("createBy", order.getSupplierID());
			orderService.createOrderHistory(pd);
			// TODO  配货完成后自动调整库存
			if(times==1){
				result=JsonResult.success("200", "配货成功");
			}else{
				result=JsonResult.error("300", "配货失败");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return result;
	}
	
	/**
	 * 供应商订单发货的处理
	 * @return
	 */
	@RequestMapping(value="/sendOrderStatus")
	@ResponseBody
	public JsonResult sendOrderStatus(HttpSession session,String id){
		JsonResult result=new JsonResult();
		PageData pd = new PageData();
		int status = 4;
		pd.put("id", id);
		pd.put("orderStatus",status);
		//TODO 有权限的用户才可以进行发货处理
		/*if("1".equals(user.getAuthorityState())){//默认0为有权限      1:没有权限
			result=JsonResult.error("300", "没有权限进行发货");
			return result;
		}*/
		try {
			//修改状态
			int flag=orderService.updateOrderStatus(pd);
			//查询订单的基本信息
			OrderEntity order=orderService.findOneOrder(pd);
			pd.put("orderHistoryID", UUID.randomUUID().toString());
			pd.put("orderStatus", status);
			pd.put("createTime", DateUtil.getTime());
			pd.put("createBy", order.getSupplierID());
			List<OrderGoodsSpecEntity> orderDetailList = orderService
					.OrderGoodsSpecEntity(pd);
			double sales = 0;
			for (int i = 0; i < orderDetailList.size(); i++) {
				OrderGoodsSpecEntity ode = orderDetailList.get(i);
				// /去除已发货的预约库存量S
				pd.put("inventory", ode.getInventory());
				pd.put("reserveCount", ode.getReserveCount() - ode.getNumber());
				sales = ode.getSales() + ode.getNumber();
				pd.put("goodsSpecId", ode.getGoodsSpecId());
				pd.put("sales", sales);
				orderService.updateGoodsSpecInventory(pd);
			}
			//如果 该订单包含商品信息,则发货更新商品销量
			if (orderDetailList.size() > 0) {
				String goodsSpecId = pd.get("goodsSpecId").toString();
				pd.put("goodsSpecId", goodsSpecId);
				//查询计算 该商品销量
				PageData goodsIDObject = orderService.findGoodsID(pd);
				String goodsID = goodsIDObject.getString("goodsId");
				pd.put("sales", sales);
				pd.put("goodsID", goodsID);
				//更新商品销量
				orderService.updateGoodsSale(pd);
			}
			if(flag==1){
				result=JsonResult.success("200", "发货成功");
			}else{
				result=JsonResult.error("300", "发货失败");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return result;
	}
	/**
	 * 查看订单发货明细
	 * @return
	 */
	@RequestMapping(value="/orderSendDetail")
	public String orderSendDetail(String id,Model model){
		OrderEntity order=null;
		PageData pd = new PageData();
		pd.put("orderID", id);
		try {
			//根据订单id查询明细
			order=orderService.findByOId(pd);
			model.addAttribute("order", order);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return "order/ordersenddetail";
	}
	@RequestMapping(value="/loadOrderDetail")
	@ResponseBody
    public void loadOrderDetail(String id){
		PageData pd = new PageData();
		pd.put("orderID", id);
		try {
			List<OrderGoodsSpecEntity> goods = orderService.OrderGoodsSpecEntity(pd);
			
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
     }
}